﻿using LuaInterface;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Demo;

public class LuaBehaviourScript : MonoBehaviour
{
    public string scriptName;
    public LuaTable self_;
    protected virtual void Awake()
    {
        //require lua文件，得到返回的LUA类
        LuaTable metatable = metatable = (LuaTable)LuaManager.Instance.require(scriptName);

        //从类中找到New函数
        LuaFunction lnew = (LuaFunction)metatable["New"];
        //执行New函数生成脚本对象
        object[] results = lnew.LazyCall(metatable, this);
        //存贮脚本对象
        self_ = (LuaTable)results[0];

        //给脚本对象设置上常用的属性
        self_["transform"] = transform;
        self_["gameObject"] = gameObject;
        self_["name"] = scriptName;

        //尝试调用脚本对象的Awake函数
        // LuaBehaviour.CallMethod(scriptName, "Awake",gameObject);
        CallMethod("Awake");
    }

    protected virtual void Start()
    {
        CallMethod("Start");
    }

    protected virtual void OnDestroy()
    {
        CallMethod("OnDestroy");
        if (self_ != null)
        {
            self_.Dispose();
            self_ = null;
        }
    }

    protected object[] CallMethod(string func, params object[] args)
    {
        if (self_.GetLuaState() != null)
        {
            //查找LUA函数
            LuaFunction lfunc = (LuaFunction)self_[func];
            if (lfunc == null)
            {
                return null;
            }

            //调用LUA函数。等价于lua语句“self:func(...)”
            int oldTop = lfunc.BeginPCall();
            lfunc.Push(self_); //将self作为第一个参数传入
            lfunc.PushArgs(args);
            lfunc.PCall();
            object[] objs = LuaManager.Instance.lua.CheckObjects(oldTop);
            lfunc.EndPCall();
            return objs;
        }
        return null;
    }
}
